<template>
  <div id="image"
       ref='image'
       :style="containerStyle"
       :class="{hidden:FilePath}"
       @dblclick="loadImage"
       @mousewheel="zoomImage">
    <img v-if="FilePath" v-show="getFilePath(FilePath,'IMAGE')" class="image_file" :style="imageStyle"
         :src="getFilePath(FilePath,'IMAGE')" draggable="false"
         @pointerdown="SetImageDisplayArea()">
    <img v-else class="open_file" title="打开" src="~@/assets/img/SlideEditor/image_icon.png" draggable="false"
         @click="loadImage"/>
  </div>
</template>
<script>
  import action from '../../common/typeActions'
  import {mapActions, mapGetters} from 'vuex'
  import path from 'path'

  let remote = ''

  export default {
    name: 'Image',
    props: {
      ID: {type: String},
      FilePath: {type: String},
      FileCode: {type: String},
      containerStyle: {type: Object},
      isReadonly: {type: Boolean, default: false},
      zoom: {
        type: Object,
        default: () => {
          return {zoomScale: 1, top: 0, left: 0}
        }
      }
    },
    data: function () {
      return {}
    },
    computed: {
      ...mapGetters(['getFilePath']),
      imageStyle: {
        get () {
          return {
            width: `${this.zoom.zoomScale * 100}%`,
            height: `${this.zoom.zoomScale * 100}%`,
            top: `${this.zoom.top / 2 * 100}%`,
            left: `${this.zoom.left / 2 * 100}%`
          }
        }
      }
    },
    methods: {
      ...mapActions({
        addExternalFile: action.SLIDEEDITOR.AddExternalFile,
        setElementAttr: action.SLIDEEDITOR.SetElementAttr,
        setActiveElementAttr: action.SLIDEEDITOR.SetActiveElementAttr
      }),
      zoomImage: function () {
        if (
          !event.ctrlKey ||
          !this.$parent ||
          !this.$parent.Activated ||
          (this.zoom.zoomScale <= 1 && event.deltaY > 0)
        ) {
          return
        }
        let deltaY = event.deltaY < 0 ? 0.1 : -0.1
        let left = this.zoom.left - deltaY
        let top = this.zoom.top - deltaY
        if (deltaY < 0) {
          let scale = (this.zoom.zoomScale - 1) / 2
          if (scale > Math.abs(this.zoom.left)) {
            left = 0
          } else if (scale < Math.abs(this.zoom.left)) {
            left = this.zoom.zoomScale <= 1.1 ? 0 : -scale * 2
          }
          if (scale > Math.abs(this.zoom.top)) {
            top = 0
          } else if (scale < Math.abs(this.zoom.top)) {
            top = this.zoom.zoomScale <= 1.1 ? 0 : -scale * 2
          }
        }

        this.setActiveElementAttr({
          attrName: 'zoom',
          attrValue: {
            zoomScale: this.zoom.zoomScale + deltaY,
            top: top,
            left: left
          }
        })
      },
      SetImageDisplayArea: function () {
        let self = this
        if (!event.ctrlKey || event.buttons !== 1) return
        let loc = {x: event.offsetX, y: event.offsetY}
        event.target.onmousemove = () => {
          if (!event.ctrlKey || event.buttons !== 1) {
            event.target.onmouseup = event.target.onmousemove = null
            return
          }
          let moveWidth = event.offsetX - loc.x
          let moveHeight = event.offsetY - loc.y
          // 向右移动
          if (moveWidth > 0) {
            moveWidth =
              event.target.offsetLeft + moveWidth > 0
                ? Math.abs(event.target.offsetLeft)
                : moveWidth
          } else if (moveWidth < 0) {
            let containerWidth = event.target.offsetParent.offsetWidth
            let imgWidth = event.target.offsetWidth
            let imgLeft = event.target.offsetLeft
            moveWidth =
              Math.abs(imgLeft + moveWidth) >= imgWidth - containerWidth
                ? 0
                : moveWidth
          }
          // 向下移动
          if (moveHeight > 0) {
            moveHeight =
              event.target.offsetTop + moveHeight > 0
                ? Math.abs(event.target.offsetTop)
                : moveHeight
          } else if (moveHeight < 0) {
            let containerHeight = event.target.offsetParent.offsetHeight
            let imgHeight = event.target.offsetHeight
            let imgTop = event.target.offsetTop
            moveHeight =
              Math.abs(imgTop + moveHeight) >= imgHeight - containerHeight
                ? 0
                : moveHeight
          }
          this.setActiveElementAttr({
            attrName: 'zoom',
            attrValue: {
              zoomScale: this.zoom.zoomScale,
              top:
                self.zoom.top +
                moveHeight * self.zoom.zoomScale / event.target.height,
              left:
                self.zoom.left +
                moveWidth * self.zoom.zoomScale / event.target.width
            }
          })
          loc = {x: event.offsetX, y: event.offsetY}
        }
        event.target.onpointerup = () => {
          event.target.onpointerup = event.target.onpointermove = null
        }
      },
      // 上传图片
      loadImage: function () {
        let self = this
        if (self.isReadonly) return
        if (remote) {
          let extensions = {
            properties: ['openFile', 'showHiddenFiles'],
            filters: [{name: 'Image', extensions: ['png', 'jpg', 'bmp']}]
          }
          remote.dialog.showOpenDialog(
            remote.getCurrentWindow(),
            extensions,
            async rs => {
              try {
                if (!rs) return
                await this.addExternalFile({
                  id: self.ID,
                  fileID: self.FileCode,
                  imageID: self.FilePath,
                  path: rs[0]
                })
                self.$emit('ImageLoadFinish', {ID: self.ID})
              } catch (error) {
                self.$alert(error.message, '提示')
              }
            }
          )
        } else {
          let input = document.createElement('input')
          input.type = 'file'
          input.multiple = false
          input.accept = 'image/png, image/jpeg, image/bmp'
          input.onchange = async () => {
            if (event.target.files.length > 0) {
              this.loadState = false
              if (!/bmp|png|jpe?g/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择BMP、PNG、JPG格式的图片文件')
              let formData = new FormData()
              formData.append('dbPath', this.$store.state.appearCourt.casePath)
              for (let i = 0; i < event.target.files.length; i++) {
                formData.append('files', event.target.files[i])
              }
              let uploadFiles = await this.$api.post.uploadFiles(formData)
              await this.addExternalFile({
                id: this.ID,
                fileID: this.FileCode,
                imageID: this.FilePath,
                file: uploadFiles[0]
              })

              this.$emit('ImageLoadFinish', {ID: this.ID})
              this.loadState = true
            }
          }
          input.click()

          // this.openFileDialog(extensions, async () => {
          //   if (event.target.files.length > 0) {
          //     if (!/bmp|png|jpe?g/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择BMP、PNG、JPG格式的图片文件')
          //
          //     try {
          //       /* eslint-disable new-cap */
          //       let uploadFileBySlice = new this.$methods.uploadFileBySlice({
          //         file: event.target.files[0],
          //         fileType: 'caseAccessory'
          //       })
          //       uploadFileBySlice.eventBus.on('success', async data => {
          //         await this.addExternalFile({
          //           id: this.ID,
          //           fileID: this.FileCode,
          //           imageID: this.FilePath,
          //           path: {Files: [data]}
          //         })
          //
          //         this.$emit('ImageLoadFinish', {ID: this.ID})
          //         this.loadState = true
          //       })
          //       uploadFileBySlice.eventBus.on('fail', err => {
          //         this.$alert(err.message, '错误', {type: 'error'})
          //         this.loadState = true
          //       })
          //       this.loadState = false
          //       uploadFileBySlice.start()
          //     } catch (error) {
          //       this.$alert(error.message, '提示')
          //     }
          //   }
          // })
        }
      }
    }
  }
</script>
<style>
  #image {
    width: 100%;
    height: 100%;
  }

  .hidden {
    position: absolute;
    overflow: hidden;
  }

  #image .image_file {
    width: 100%;
    height: 100%;
    float: left;
    position: absolute;

    object-fit: fill;
  }

  #image .open_file {
    position: absolute;
    top: calc(50% - 16px);
    left: calc(50% - 16px);
    cursor: pointer;
  }
</style>
